package com.example.controller.auth;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.common.result.Result;
import com.example.entity.auth.*;
import com.example.entity.vo.auth.SysUserQueryVo;
import com.example.entity.yifei.Dscma;
import com.example.mapper.DscmaMapper;
import com.example.service.auth.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author ssy
 * @since 2023-09-15
 */
@Api(tags = "用户管理接口")
@RestController
@RequestMapping("/api/system/sysUser")
public class SysUserController {

    @Resource
    private SysUserService service;

    @Resource
    private SysPostService postService;

    @Resource
    private SysDeptService sysDeptService;

    @Resource
    private SysUserRoleService sysUserRoleService;

    @Resource
    private SysRoleService sysRoleService;

    @Resource
    private DscmaMapper dscmaMapper;

    @ApiOperation(value = "更新状态")
    @GetMapping("updateStatus/{id}/{status}")
    public Result updateStatus(@PathVariable Long id, @PathVariable Integer status) {
        service.updateStatus(id,status);
        return Result.success();
    }

    @ApiOperation("用户条件分页查询")
    @GetMapping("/getUserInfo")
    public Result<SysUser> index(SysUserQueryVo sysUserQueryVo) {
        //封装条件，判断条件值不为空
        SysUser user = new SysUser();
        // 先去 SQL SERVER 的 DSCSYS数据库的 DSCMA 用keyword去找DS的信息
        Dscma dscma = dscmaMapper.selectOne(new LambdaQueryWrapper<Dscma>().eq(Dscma::getMa001, sysUserQueryVo.getKeyword()));
        if(dscma == null) return Result.error("用户不存在");
        //  去MYSQL的用户角色关联表 用DS  username   name   roleList
        user.setUsername(dscma.getMa001().trim());
        user.setName(dscma.getMa002().trim());
        List<SysRole> roleList = service.getRoleList(sysUserQueryVo.getKeyword());
        user.setRoleList(roleList);

        return Result.success(user);

    }

    //用户条件分页查询
    @ApiOperation("用户条件分页查询")
    @GetMapping("{page}/{limit}")
    public Result<IPage<SysUser>> index(@PathVariable Long page,
                        @PathVariable Long limit,
                        SysUserQueryVo sysUserQueryVo) {
        //创建page对象
        Page<SysUser> pageParam = new Page<>(page,limit);

        //封装条件，判断条件值不为空
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        //获取条件值
        String username = sysUserQueryVo.getKeyword();
        String createTimeBegin = sysUserQueryVo.getCreateTimeBegin();
        String createTimeEnd = sysUserQueryVo.getCreateTimeEnd();
        //判断条件值不为空
        //like 模糊查询
        if(!StringUtils.isEmpty(username)) {
            wrapper.like(SysUser::getUsername,username);
        }
        //ge 大于等于
        if(!StringUtils.isEmpty(createTimeBegin)) {
            wrapper.ge(SysUser::getCreateTime,createTimeBegin);
        }
        //le 小于等于
        if(!StringUtils.isEmpty(createTimeEnd)) {
            wrapper.le(SysUser::getCreateTime,createTimeEnd);
        }

        //调用mp的方法实现条件分页查询
        IPage<SysUser> pageModel = service.page(pageParam, wrapper);
        List<SysRole> roleList = new ArrayList<>();
        for (SysUser record : pageModel.getRecords()) {
            LambdaQueryWrapper<SysUserRole> wrapper1 = new LambdaQueryWrapper<>();
            wrapper1.eq(SysUserRole::getUserId,record.getId());
            List<SysUserRole> list = sysUserRoleService.list(wrapper1);
            for (SysUserRole sysUserRole : list) {
                SysRole byId = sysRoleService.getById(sysUserRole.getRoleId());
                roleList.add(byId);
            }
            record.setRoleList(roleList);
            if (record.getPostId()==null && record.getDeptId()==null) continue;
            SysPost post = postService.getById(record.getPostId());
            if (post!=null){
                record.setPostName(post.getName());
            }
            SysDept dept = sysDeptService.getById(record.getDeptId());
            if (dept!=null) {
                record.setDeptName(dept.getName());
            }
        }
        return Result.success(pageModel);
    }

    @ApiOperation(value = "获取用户")
    @GetMapping("get/{id}")
    public Result get(@PathVariable Long id) {
        SysUser user = service.getById(id);
        return Result.success(user);
    }

//    @ApiOperation(value = "保存用户")
//    @PostMapping("save")
//    public Result save(@RequestBody SysUser user) {
//        //密码进行加密，使用MD5
//        String passwordMD5 = MD5.encrypt(user.getPassword());
//        user.setPassword(passwordMD5);
//
//        service.save(user);
//        return Result.success();
//    }

    @ApiOperation(value = "更新用户")
    @PutMapping("update")
    public Result updateById(@RequestBody SysUser user) {
        service.updateById(user);
        return Result.success();
    }

    @ApiOperation(value = "删除用户")
    @DeleteMapping("remove/{id}")
    public Result remove(@PathVariable Long id) {
        service.removeById(id);
        return Result.success();
    }

}

